package com.ruoyi.xiaoshouchuku.controller;

import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

import com.ruoyi.cangku.domain.Cangku;
import com.ruoyi.cangku.service.ICangkuService;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.goods.domain.Goods;
import com.ruoyi.goods.service.IGoodsService;
import com.ruoyi.kucunpandian.domain.Kucunpandian;
import com.ruoyi.kucunpandian.service.IKucunpandianService;
import com.ruoyi.shangpinxinxi.domain.Shangpinxinxi;
import com.ruoyi.shangpinxinxi.service.IShangpinxinxiService;
import com.ruoyi.xiaoshouchuku.domain.XiaoshouChuku2;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.xiaoshouchuku.domain.XiaoshouChuku;
import com.ruoyi.xiaoshouchuku.service.IXiaoshouChukuService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletRequest;

/**
 * 销售出库Controller
 * 
 * @author ruoyi
 * @date 2023-01-10
 */
@Controller
@RequestMapping("/xiaoshouchuku/chukuTest")
public class XiaoshouChukuController extends BaseController
{
    private String prefix = "xiaoshouchuku/chukuTest";

    @Autowired
    private IXiaoshouChukuService xiaoshouChukuService;
    @Autowired
    private IKucunpandianService kucunpandianService;
    @Autowired
    private ICangkuService cangkuService;
    @Autowired
    private IShangpinxinxiService shangpinxinxiService;

    @Autowired
    private IKucunpandianService cangkupandianService;

    @RequiresPermissions("xiaoshouchuku:chukuTest:view")
    @GetMapping()
    public String chukuTest()
    {
        return prefix + "/chukuTest";
    }

    /**
     * 查询销售出库列表
     */
    @RequiresPermissions("xiaoshouchuku:chukuTest:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(HttpServletRequest request, XiaoshouChuku xiaoshouChuku)
    {
        startPage();
        String a = request.getSession().getAttribute("QuanXian").toString();
        if (a.equals("0") && (xiaoshouChuku == null || xiaoshouChuku.getChukuCangku().equals(""))) {

            XiaoshouChuku xiaoshouChuku1 = new XiaoshouChuku();
            xiaoshouChuku1.setChukuCangku(request.getSession().getAttribute("name4user").toString());
            List<XiaoshouChuku> list = xiaoshouChukuService.selectXiaoshouChukuList(xiaoshouChuku1);
            return getDataTable(list);

        }else {
            List<XiaoshouChuku> list = xiaoshouChukuService.selectXiaoshouChukuList(xiaoshouChuku);
            return getDataTable(list);
        }


        /*startPage();
        if (request.getSession().getAttribute("QuanXian") != "1"&& xiaoshouChuku == null) {
            List<Cangku> namee2cangku = cangkuService.selectCangkuAll();
            XiaoshouChuku xiaoshouChuku1 = new XiaoshouChuku();
            for (Cangku c:namee2cangku) {
                if (c.getCangkuName().equals(request.getSession().getAttribute("name4user").toString())) {
                    xiaoshouChuku1.setChukuCangku(c.getCangkuName());
                }
            }
            List<XiaoshouChuku> list = xiaoshouChukuService.selectXiaoshouChukuList(xiaoshouChuku1);
            return getDataTable(list);
        }else {
            List<XiaoshouChuku> list = xiaoshouChukuService.selectXiaoshouChukuList(xiaoshouChuku);
            return getDataTable(list);
        }*/

    }

    /**
     * 导出销售出库列表
     */
    @RequiresPermissions("xiaoshouchuku:chukuTest:export")
    @Log(title = "销售出库", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(HttpServletRequest request,XiaoshouChuku xiaoshouChuku)
    {
        String a = request.getSession().getAttribute("QuanXian").toString();
        if (a.equals("1")) {
            List<XiaoshouChuku> list = xiaoshouChukuService.selectXiaoshouChukuList(xiaoshouChuku);
            ExcelUtil<XiaoshouChuku> util = new ExcelUtil<XiaoshouChuku>(XiaoshouChuku.class);
            return util.exportExcel(list, "销售出库数据");
        }
        else {
            List<XiaoshouChuku2> list = xiaoshouChukuService.selectXiaoshouChukuListAndQuanXian(xiaoshouChuku);
            ExcelUtil<XiaoshouChuku2> util = new ExcelUtil<XiaoshouChuku2>(XiaoshouChuku2.class);
            return util.exportExcel(list, "销售出库数据");
        }

    }

    /**
     * 新增销售出库
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存销售出库
     */
    @RequiresPermissions("xiaoshouchuku:chukuTest:add")
    @Log(title = "销售出库", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(XiaoshouChuku xiaoshouChuku)
    {
        danhaoSet(xiaoshouChuku);
        Shangpinxinxi shangpinxinxi = shangpinxinxiService.selectShangpinxinxiByBianHao(xiaoshouChuku.getGoodId());
        Kucunpandian kucunpandian = kucunpandianService.selectCangkupandianByGoodIdAndCangKuNameAndGoodName(
                xiaoshouChuku.getGoodId(),xiaoshouChuku.getChukuCangku(),shangpinxinxi.getShangpinName());
        if (kucunpandian == null) {
        return toAjax(-1);
    }
        long KuCunNew = kucunpandian.getKuncun()
                -xiaoshouChuku.getShuliang().longValue();
        kucunpandian.setKuncun(KuCunNew);
        if (KuCunNew < 0) {
            return toAjax(false);
        }
        kucunpandianService.updateKucunpandian(kucunpandian);

        Double zongjiner=xiaoshouChuku.getChukuDanjia()* xiaoshouChuku.getShuliang();
        xiaoshouChuku.setJiner(zongjiner);
        xiaoshouChuku.setGoodGuige(shangpinxinxi.getShangpinGuige());
        xiaoshouChuku.setGoodName(xiaoshouChuku.getGoodName());
        xiaoshouChuku.setShangpinLeibie(shangpinxinxi.getShangpinLeibie());

        return toAjax(xiaoshouChukuService.insertXiaoshouChuku(xiaoshouChuku));
    }

    /**
     * 修改销售出库
     */
    @RequiresPermissions("xiaoshouchuku:chukuTest:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        XiaoshouChuku xiaoshouChuku = xiaoshouChukuService.selectXiaoshouChukuById(id);
        mmap.put("xiaoshouChuku", xiaoshouChuku);
        return prefix + "/edit";
    }

    /**
     * 修改保存销售出库
     */
    @RequiresPermissions("xiaoshouchuku:chukuTest:edit")
    @Log(title = "销售出库", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(XiaoshouChuku xiaoshouChuku)
    {
        Shangpinxinxi shangpinxinxi = shangpinxinxiService.selectShangpinxinxiByBianHao(xiaoshouChuku.getGoodId());
        Kucunpandian kucunpandian = kucunpandianService.selectCangkupandianByGoodIdAndCangKuNameAndGoodName(
                xiaoshouChuku.getGoodId(),xiaoshouChuku.getChukuCangku(),shangpinxinxi.getShangpinName());
        XiaoshouChuku xiaoshouChuku1 =
                xiaoshouChukuService.selectXiaoshouChukuBychukuDanhao(
                        xiaoshouChuku.getChukuDanhao());
        Long KuCunNew = kucunpandian.getKuncun()
                -xiaoshouChuku.getShuliang().longValue()
                +xiaoshouChuku1.getShuliang().longValue();
        kucunpandian.setKuncun(KuCunNew);
        if (KuCunNew < 0) {
            return toAjax(false);
        }
        kucunpandianService.updateKucunpandian(kucunpandian);

        Double zongjiner=xiaoshouChuku.getChukuDanjia()* xiaoshouChuku.getShuliang();
        xiaoshouChuku.setJiner(zongjiner);
        xiaoshouChuku.setShangpinLeibie(shangpinxinxi.getShangpinLeibie());
        xiaoshouChuku.setGoodName(shangpinxinxi.getShangpinName());
        xiaoshouChuku.setGoodGuige(shangpinxinxi.getShangpinGuige());

        return toAjax(xiaoshouChukuService.updateXiaoshouChuku(xiaoshouChuku));
    }

    /**
     * 删除销售出库
     */
    @RequiresPermissions("xiaoshouchuku:chukuTest:remove")
    @Log(title = "销售出库", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        if (!ids.contains(",")) {
            kucunSet(ids);
        }else {
            String[] idlist = Convert.toStrArray(ids);
            for (String s:idlist) {
                kucunSet(s);
            }
        }
        return toAjax(xiaoshouChukuService.deleteXiaoshouChukuByIds(ids));
        /*Long id = Long.valueOf(ids);
        XiaoshouChuku xiaoshouChuku = xiaoshouChukuService.selectXiaoshouChukuById(id);
        Kucunpandian cangkupandian = new Kucunpandian();

        cangkupandian.setCangkuName(xiaoshouChuku.getChukuCangku());

        cangkupandian.setGoodId(xiaoshouChuku.getGoodId());
        cangkupandian.setGoodName(xiaoshouChuku.getGoodName());
        cangkupandian.setGoodSpecification(xiaoshouChuku.getBeizhu());


        kucunpandianService.updateKucunpandian(cangkupandian);*/

        //goodsinsert(xiaoshouChuku);

    }

    private void kucunSet(String ids) {
        Long id = Long.valueOf(ids);
        XiaoshouChuku xiaoshouChuku = xiaoshouChukuService.selectXiaoshouChukuById(id);
        Kucunpandian cangkupandian = new Kucunpandian();

        cangkupandian.setCangkuName(xiaoshouChuku.getChukuCangku());
        cangkupandian.setGoodId(xiaoshouChuku.getGoodId());
        cangkupandian.setGoodName(xiaoshouChuku.getGoodName());
        cangkupandian.setGoodSpecification(xiaoshouChuku.getGoodGuige());

        Kucunpandian kucunpandian = cangkupandianService.selectCangkupandianByGoodIdAndCangKuNameAndGoodName(xiaoshouChuku.getGoodId().replace("\n",""), xiaoshouChuku.getChukuCangku(),xiaoshouChuku.getGoodName());
//        cangkupandian.setId(kucunpandian.getId());
        cangkupandian.setShangpinLeibie(xiaoshouChuku.getShangpinLeibie());
        cangkupandian.setKuncun(kucunpandian.getKuncun() + xiaoshouChuku.getShuliang().longValue());

        cangkupandianService.updateKucunpandian(cangkupandian);
    }


    @PostMapping("/chukuSaoma")
    @ResponseBody
    public AjaxResult chukuSaoma(HttpServletRequest  request, String msg)
    {
        //现在是扫一次录一单进去，不用批量写入
        // 因此这里的msg只传了商品编号过来
        //所以需要关联查询商品表才能写入销售出库
        XiaoshouChuku xiaoshouChuku = new XiaoshouChuku();
        Shangpinxinxi shangpinxinxi;String[] msgstr = new String[10];
        if (msg.indexOf("，") >= 5||msg.indexOf(",")>=5) {
            if (msg.contains("，")) {
                msgstr = msg.split("，");
            }else{
                msgstr = msg.split(",");
            }

            shangpinxinxi = shangpinxinxiService.selectShangpinxinxiByBianHao(msgstr[0]);
        }else {
            shangpinxinxi = shangpinxinxiService.selectShangpinxinxiByBianHao(msg.replace("\n",""));
        }


        danhaoSet(xiaoshouChuku);

        xiaoshouChuku.setChukuDate(DateUtils.getNowDate());
        xiaoshouChuku.setPaymentMethod("0");
        xiaoshouChuku.setChukuJingshouren("");
        xiaoshouChuku.setChukuCangku(request.getSession().getAttribute("name4user").toString());
        xiaoshouChuku.setGoodId(msg.replace("\n",""));
        xiaoshouChuku.setShangpinLeibie(shangpinxinxi.getShangpinLeibie());
        xiaoshouChuku.setGoodName(shangpinxinxi.getShangpinName());
        xiaoshouChuku.setGoodGuige(shangpinxinxi.getShangpinGuige());
        xiaoshouChuku.setShuliang(1.0);
        xiaoshouChuku.setChukuDanjia(shangpinxinxi.getShangpinLingshoujia());
        Kucunpandian kucunpandian;
        if (msgstr[0] != null) {
            kucunpandian = cangkupandianService.selectCangkupandianByGoodIdAndCangKuNameAndGoodName(
                    msgstr[0],
                    xiaoshouChuku.getChukuCangku(),
                    xiaoshouChuku.getGoodName());
        }else {
            kucunpandian = cangkupandianService.selectCangkupandianByGoodIdAndCangKuNameAndGoodName(
                    msg.replace("\n",""),
                    xiaoshouChuku.getChukuCangku(),
                    xiaoshouChuku.getGoodName());
        }

        Long kucunNew = kucunpandian.getKuncun()-1;
        kucunpandian.setKuncun(kucunNew);
        if (msg.indexOf("，") >= 5||msg.indexOf(",")>=5) {
            if (msg.contains("，")) {
                msgstr = msg.split("，");
            }else{
                msgstr = msg.split(",");
            }
            xiaoshouChuku.setGoodId(msgstr[0]);
            xiaoshouChuku.setGoodName(msgstr[1]);
            String s = "";
            for (int i = 2; i < msgstr.length; i++) {
                s = s+msgstr[i];
            }
            xiaoshouChuku.setBeizhu(s);
        }
        kucunpandianService.updateKucunpandian(kucunpandian);
        if (kucunpandianService.updateKucunpandian(kucunpandian) == -1) {
            return toAjax(-1);
        }

        if (request.getSession().getAttribute("QuanXian").toString().equals("1")) {
            xiaoshouChuku.setZongbudijia(shangpinxinxi.getShangpinDijia());
        }
        xiaoshouChuku.setJiner(shangpinxinxi.getShangpinLingshoujia());
        return toAjax(xiaoshouChukuService.insertXiaoshouChuku(xiaoshouChuku));
    }

    private void danhaoSet(XiaoshouChuku xiaoshouChuku) {
        String numstr = xiaoshouChukuService.selectXiaoshouChukuIdByLastOne();
        int num;
        if (numstr == null) {
            num = 1;
        }else {
            num = Integer.parseInt(numstr)+1;
        }
        String b = String.valueOf(num);
        if (String.valueOf(num).length() < 8) {
            int a = 8-b.length();
            for (int j = 0; j < a; j++) {
                b="0" + b;
            }
        }
        xiaoshouChuku.setChukuDanhao(b);
    }
}
